package com.ddxcloud.movie.utils;

import com.ddxcloud.common.utils.RedisUtil;
import com.ddxcloud.movie.config.common.JwtProperties;
import com.ddxcloud.movie.data.constants.HeadersConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class JwtUtil {

    @Resource
    JwtProperties jwtProperties;

    private static String secretKey;

    @PostConstruct
    public void init() {
        secretKey = jwtProperties.getSecretKey();
    }

    public static long timeMillis = 30 * 24 * 60 * 60 * 1000L;

    private static RedisUtil redisUtil;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        JwtUtil.redisUtil = redisUtil;
    }

    public static String getRedisPrefix() {
        return HttpHeaders.AUTHORIZATION + ":" + getRequest().getHeader(HeadersConstant.CHANNEL_ID) + ":";
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert ra != null;
        return ra.getRequest();
    }

    /**
     * 生成Token
     * @param claims
     * @return
     */
    public static String createJWT(Map<String, Object> claims) {
        String token = Jwts.builder()
                .signWith(Keys.hmacShaKeyFor(secretKey.getBytes()), Jwts.SIG.HS256)
                .expiration(new Date(System.currentTimeMillis() + timeMillis))
                .claims(claims)
                .compact();
        redisUtil.setEx(getRedisPrefix() + token, token, timeMillis, TimeUnit.MILLISECONDS);
        return token;
    }

    /**
     * 解析Token
     * @param token
     * @return
     */
    public static Jws<Claims> parseJWT(String token) {
        return Jwts.parser()
                .verifyWith(Keys.hmacShaKeyFor(secretKey.getBytes()))
                .build()
                .parseSignedClaims(token);
    }

    /**
     * 校验Token
     * @param token
     * @return
     */
    public static Boolean verifyJWT(String token) {
        String redisKey = getRedisPrefix() + token;
        if (redisUtil.hasKey(redisKey)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
